<?php class Bootstraps extends Zone_Bootstraps{
	public function init(){
		if( $this->app->getModuleName() == 'Cron' ){
			return true;	
		}
	
		/* Use json script */		
		$is_json = isset($_REQUEST['_json'] );
		if( $is_json ){
			//header('Cache-Control: no-cache, must-revalidate');
			//header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
			header('Content-type: application/json');
			$this->app->setLayoutJSON();
		}	

		if( $this->app->getModuleName() == 'Logout' ){
			return true;	
		}
		
		//var_dump($_COOKIE);
		if( !is_login() ){
			if( is_remember_login() ){
				list($username,$password) = get_remember_login();

				$user = $this
					->Model
					->fetchRow("SELECT * 
						FROM `users` 
						WHERE 
							`is_deleted`='no' 
							AND UPPER(`username`) = UPPER('$username') 
							AND `password`='$password'");
				if( $user ){
					$this->Model->update('users',array(
						date_login => new Model_Expr('NOW()') 
					),"`ID`='{$user['ID']}'");
					
					$this->setRole( $user['ID'] );
					save_login($user,$username,$password);
					if( $this->app->getModuleName() == 'Login' ){
						redirect( '/User', true );
					}					
					return true;	
				}	
			}			
			
			if( $this->app->getModuleName() != "Login" ){
				//only direct when in main action
				if( $this->env ){
					if( $is_json ){
						$this->app->setJSON(array(
							error_login	=> true,
							error_code	=> 401	
						));
						return $this->stop();
					}else{				
						redirect( '/Login', true );	
					}	
				}	
			}
		}else{
			if( !$this->Model->fetchRow("SELECT * FROM `users` WHERE `ID`='".get_user_id()."' AND `is_deleted`='no'") ){
				clear_login();
				redirect( '/Login', true );
				return false;
			}
			$this->setRole( get_user_id() );
			if( $this->app->getModuleName() == 'Login' ){
				redirect( '/User', true );
			}
		}
	
	}		
	
	protected function setRole( $user_id ){
		$user = $this->Model->fetchRow("SELECT 
			IF(`a`.`inherit_roles`='yes',`b`.`roles`,`a`.`roles`) as `role`,
			`settings`	
			FROM `users` as `a`
			LEFT JOIN `groups` as `b`
				ON `b`.`ID`=`a`.`group_id`
			WHERE `a`.`is_deleted`='no' AND `a`.`ID`='$user_id'");
		
		$this->app->setConfig(array(
			user => get_query_configs($user['settings'])
		));
		
		$this->app->setRole( array_map('trim', explode(',',$user['role']) ) );
	}	
} 